<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import type { FormInstance, FormRules } from "element-plus";
import { ElMessage } from 'element-plus';
import { ArrowLeft } from '@element-plus/icons-vue';
import { userApi } from '@/api/customer';
import { 
  setToken, 
  setUserInfo, 
  setUserRole, 
  setRememberMe, 
  isRememberMe,
  getRememberedUsername,
  getRememberedPassword
} from '@/utils/auth';

const router = useRouter();
const loading = ref(false);
const loginFormRef = ref<FormInstance>();

const loginForm = reactive({
  username: '',
  password: '',
  rememberMe: false,
});

const loginRules = reactive<FormRules>({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 1, max: 50, message: '用户名长度1-50位', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 128, message: '密码长度6-128位', trigger: 'blur' }
  ]
});

// 页面加载时检查是否有记住的用户名和密码
onMounted(() => {
  // 检查是否记住了登录信息
  if (isRememberMe()) {
    const savedUsername = getRememberedUsername();
    const savedPassword = getRememberedPassword();
    
    if (savedUsername) {
      loginForm.username = savedUsername;
    }
    
    if (savedPassword) {
      loginForm.password = savedPassword;
    }
    
    loginForm.rememberMe = true;
    
    // 自动登录
    handleLogin(loginFormRef.value);
  }
});

// 处理登录
const handleLogin = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  
  await formEl.validate(async (valid: boolean) => {
    if (valid) {
      try {
        loading.value = true;
        console.log("开始顾客登录请求，用户名:", loginForm.username);
        
        const res = await userApi.login({
          username: loginForm.username,
          password: loginForm.password
        });
        
        console.log("完整响应对象:", res);
        
        // 检查HTTP响应状态
        if (res.status !== 200) {
          ElMessage.error('登录请求失败');
          loading.value = false;
          return;
        }
        
        const responseData = res.data;
        console.log("API响应数据:", responseData);
        
        if (!responseData || responseData.status !== 200) {
          const errorMsg = responseData?.message || '登录失败';
          ElMessage.error(errorMsg);
          loading.value = false;
          return;
        }
        
        // 从 responseData.data 中获取 token 和 userInfo
        const { token, userInfo } = responseData.data;
        
        if (!token) {
          ElMessage.error('登录失败：未获取到有效的token');
          loading.value = false;
          return;
        }
        
        // 检查用户角色，确保只有顾客才能登录到顾客端
        if (!userInfo || !userInfo.role || userInfo.role !== 'USER') {
          let roleMessage = '';
          if (userInfo?.role === 'MERCHANT') {
            roleMessage = '您是商家用户，请使用商家端登录';
          } else if (userInfo?.role === 'ADMIN') {
            roleMessage = '您是管理员用户，请使用管理端登录';
          } else {
            roleMessage = '用户角色验证失败，请联系管理员';
          }
          ElMessage.error(roleMessage);
          loading.value = false;
          return;
        }
        
        console.log("获取到token:", token);
        console.log("获取到用户信息:", userInfo);
        
        // 保存用户信息到全局状态（如果有的话）
        if (userInfo) {
          setUserInfo(userInfo);
        }
        
        // 处理记住密码（参考小程序版本的逻辑）
        if (loginForm.rememberMe) {
          setRememberMe(loginForm.username, loginForm.password, true);
        } else {
          setRememberMe("", "", false);
        }
        
        // 存储token和用户角色
        setToken(token, 7 * 24 * 60 * 60 * 1000); // 设置token过期时间为一周
        setUserRole("customer");
        
        ElMessage({
          message: "登录成功",
          type: "success",
          duration: 2000,
        });
        
        // 延迟跳转确保token存储完成
        setTimeout(() => {
          router.push("/customer");
        }, 500);
      } catch (error: any) {
        console.error('登录失败:', error);
        ElMessage.error(error.message || '登录失败，请检查用户名和密码');
      } finally {
        loading.value = false;
      }
    }
  });
};

// 跳转到注册页面
const goToRegister = () => {
  router.push('/customer/register');
};

// 跳转到首页
const goToHome = () => {
  router.push('/customer');
};

// 返回到用户身份选择页面
const goToRoleSelect = () => {
  router.push('/');
};
</script>

<template>
  <div class="login-container">
    <div class="login-box">
      <el-button
        icon="Back"
        circle
        @click="goToRoleSelect"
        class="back-btn"
      ></el-button>
      <div class="login-header">
        <img src="/logo.png" alt="饱了么" class="logo-image" />
        <h2>
          顾客登录
          <span class="en-title">Customer Login</span>
        </h2>
      </div>

      <el-form
        ref="loginFormRef"
        :model="loginForm"
        :rules="loginRules"
        label-position="top"
        class="login-form"
        @keyup.enter="handleLogin(loginFormRef)"
      >
        <el-form-item label="用户名" prop="username">
          <el-input
            v-model="loginForm.username"
            prefix-icon="User"
            class="tech-input"
            clearable
            maxlength="50"
            autocomplete="username"
          />
        </el-form-item>

        <el-form-item label="密码" prop="password">
          <el-input
            v-model="loginForm.password"
            type="password"
            prefix-icon="Lock"
            show-password
            class="tech-input"
            maxlength="128"
            autocomplete="current-password"
          />
        </el-form-item>

        <el-form-item>
          <el-checkbox v-model="loginForm.rememberMe">记住密码</el-checkbox>
        </el-form-item>

        <div class="form-actions">
          <el-button
            type="primary"
            @click="handleLogin(loginFormRef)"
            :loading="loading"
            class="login-btn"
          >
            登录
          </el-button>
        </div>

        <div class="form-links">
          <el-link @click="goToRegister">没有账号？点击注册</el-link>
        </div>
      </el-form>
    </div>
  </div>
</template>

<style scoped>
@import url("https://fonts.googleapis.com/css2?family=Noto+Serif+SC:wght@500&display=swap");

html,
body {
  height: 100%;
  width: 100%;
  margin: 0;
  padding: 0;
  overflow: hidden !important;
  font-family: "Noto Serif SC", "阿里巴巴普惠体", "思源宋体", "微软雅黑",
    "Microsoft YaHei", Arial, sans-serif;
}

.login-container {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  height: 100vh;
  width: 100vw;
  display: flex;
  justify-content: center;
  align-items: center;
  overflow: hidden;
  background: linear-gradient(
      rgba(255, 224, 130, 0.82),
      rgba(255, 213, 79, 0.82)
    ),
    url("https://images.pexels.com/photos/70497/pexels-photo-70497.jpeg?auto=compress&w=900&q=80")
      center center/cover no-repeat;
  color: #222;
  font-family: "Noto Serif SC", "阿里巴巴普惠体", "思源宋体", "微软雅黑",
    "Microsoft YaHei", Arial, sans-serif;
}

.login-box {
  z-index: 1;
  width: 420px;
  padding: 2.5rem 2.5rem 2rem 2.5rem;
  background: rgba(255, 245, 200, 0.97);
  border-radius: 24px;
  box-shadow: 0 4px 24px 0 #90caf933;
  border: 2.5px solid #90caf9;
  display: flex;
  flex-direction: column;
  align-items: center;
  position: relative;
  color: #a05a1c;
}

.login-header {
  position: relative;
  text-align: center;
  margin-bottom: 2rem;
}
.login-header h2 {
  font-size: 2rem;
  font-family: "PingFang SC", "Microsoft YaHei", Arial, sans-serif;
  color: #d2691e;
  letter-spacing: 0.08em;
  margin-bottom: 0.2rem;
  display: flex;
  flex-direction: column;
  align-items: center;
}
.login-header .en-title {
  font-size: 1rem;
  color: #bfa16b;
  font-family: "PingFang SC", Arial, sans-serif;
  margin-top: 0.1rem;
  letter-spacing: 0.12em;
  opacity: 0.85;
}

.back-btn {
  position: absolute;
  left: 0.8rem;
  top: 0.8rem;
  z-index: 2;
}

.login-form {
  margin-top: 1.5rem;
  width: 100%;
  color: #a05a1c;
}

.el-form-item__label {
  color: #ff9800;
  font-family: "PingFang SC", "Microsoft YaHei", Arial, sans-serif;
  letter-spacing: 0.05em;
}

.tech-input :deep(.el-input__wrapper) {
  background: #fffbe8;
  border: 1.5px solid #ffd600;
  border-radius: 14px;
  box-shadow: 0 2px 8px 0 #ffd60022;
  color: #222;
  font-size: 1.1rem;
  transition: border-color 0.3s, box-shadow 0.3s;
}
.tech-input :deep(.el-input__wrapper):focus-within {
  border-color: #ff9800;
  box-shadow: 0 0 0 2px #ffd60099, 0 0 12px 2px #ff980055;
}
.tech-input :deep(.el-input__inner) {
  background: transparent;
  color: #222;
  font-family: "PingFang SC", "Microsoft YaHei", Arial, sans-serif;
  letter-spacing: 0.05em;
}

.form-actions {
  margin-top: 1.5rem;
}

.login-btn {
  width: 100%;
  font-size: 1.1rem;
  background: linear-gradient(90deg, #fff700 0%, #ffd600 60%, #ff9800 100%);
  border: none;
  color: #fff;
  font-family: "PingFang SC", Arial, sans-serif;
  border-radius: 16px;
  box-shadow: 0 2px 12px 0 #ffd60055, 0 0 0 0 #fff;
  transition: background 0.3s, color 0.3s, box-shadow 0.3s;
  font-weight: 700;
  position: relative;
  overflow: hidden;
}
.login-btn::after {
  content: "";
  position: absolute;
  left: 0;
  top: 0;
  right: 0;
  bottom: 0;
  border-radius: 16px;
  background: linear-gradient(120deg, #fff 0%, transparent 80%);
  opacity: 0.18;
  pointer-events: none;
}
.login-btn:hover {
  background: linear-gradient(90deg, #fff700 0%, #ff9800 100%);
  color: #fffbe8;
  box-shadow: 0 4px 24px 0 #ffd60099, 0 0 0 0 #fff;
}

.form-links {
  margin-top: 1rem;
  text-align: center;
  color: #a05a1c;
}

.logo-image {
  width: 60px;
  height: 60px;
  margin-bottom: 1rem;
}
</style>
